/**
 * @Author: LongTao
 * @program: day04_longtao_springmvc_1917JA_20210108
 * @description: 用户控制层
 * @create: 2021-01-11 16:10
 * @version:1.0
 **/
package com.springmvc.longtao.smbms.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.mysql.jdbc.StringUtils;
import com.springmvc.longtao.smbms.pojo.Role;
import com.springmvc.longtao.smbms.pojo.User;
import com.springmvc.longtao.smbms.pojo.UserAndRole;
import com.springmvc.longtao.smbms.service.UserService;
import com.springmvc.longtao.smbms.utils.BaseController;
import com.springmvc.longtao.smbms.utils.BaseNameUtils;
import com.springmvc.longtao.smbms.utils.StringToDate;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

@Controller
@SuppressWarnings("all")
public class UserController{
    /**
     * 注入userService
     */
    private UserService userService;


    @Autowired
    @Qualifier("userServiceImpl")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @RequestMapping("/goLogin")
    public String goLogin() {
        return "redirect:login.jsp";
    }


    /**
     * 登录
     *
     * @param userCode
     * @param userPassword
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(@RequestParam("userCode") String userCode, @RequestParam("userPassword") String userPassword, Model model, HttpServletRequest request) {
        User user = userService.login(userCode, userPassword);
        /**
         * 若为空则提示
         */
        if (user == null) {
            //System.out.println("是否为空");
            model.addAttribute(BaseNameUtils.ERROR, "用户名或密码错误");
            return "forward:login.jsp";
        }
        /**
         * 不为空则跳转到正常页面
         */
        HttpSession session = request.getSession();
        session.setAttribute(BaseNameUtils.USERNAME, user);
        return "frame";
    }

    @RequestMapping("/noLogin")
    public String noLogin(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        session.invalidate();
        return "redirect:login.jsp";
    }

    /*   @ExceptionHandler(java.lang.ArithmeticException.class)
       public String handlerException(Model model){
           model.addAttribute("message","触发了算术异常");
           return "forward:error.jsp";
       }
   */
    @RequestMapping("/a")
    public String a() {
        int i = 1 / 0;
        return "/WEB-INF/a.jsp";
    }

    /**
     * 显示用户列表
     */
    @RequestMapping(value = {"/user/query"})
    public String userQuery(String queryUserName, Integer queryUserRole, String currentPageNo, String pageSize, Model model) {
        if (queryUserRole != null && queryUserRole == 0) {
            queryUserRole = null;
        }
        if (StringUtils.isNullOrEmpty(currentPageNo)) {
            currentPageNo = "1";
        } else {
            if (Integer.valueOf(currentPageNo) >= userService.getUserCount(queryUserName, queryUserRole)) {
                currentPageNo = String.valueOf(userService.getUserCount(queryUserName, queryUserRole));
            } else if (Integer.valueOf(currentPageNo)<=1){
                currentPageNo = "1";
            }
        }

        if (StringUtils.isNullOrEmpty(pageSize)) {
            pageSize = "7";
        }
        List<UserAndRole> userList = userService.getUserList(queryUserName, queryUserRole, Integer.valueOf(currentPageNo), Integer.valueOf(pageSize));
        List<Role> roleList = userService.queryRole();
          PageInfo<UserAndRole> pageInfo=new PageInfo<UserAndRole>(userList);
         model.addAttribute("pageInfo",pageInfo);
          System.out.println("pageInfo = " + pageInfo);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        //model.addAttribute("userList", userList);
        model.addAttribute("roleList", roleList);
        return "userlist";
    }

    /**
     * 用户添加
     *
     * @param user
     * @return
     */
    @RequestMapping("userAdd2")
    public String userAdd(@ModelAttribute(value = "user") User user, Model model) {
        List<Role> list = userService.queryRole();
        model.addAttribute("role", list);
        return "useradd";
    }

    /**
     * 添加
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public String userAdd2(@Valid User user, BindingResult result, Model model, @RequestParam(value = "multipartFile", required = false) MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        System.out.println("user = " + user);
        if (result.hasErrors()) {
            System.out.println("是否进入异常判断");
            List<Role> role = userService.queryRole();
            model.addAttribute("role", role);
            return "useradd";
        }
        //获取上传文件的名字
        String _name = multipartFile.getOriginalFilename();
        System.out.println("_name = " + _name);
        //获取上传文件的类型
        String _type = multipartFile.getContentType();
        System.out.println("_type = " + _type);
        //获取上传文件的后缀名
        String suffix = FilenameUtils.getExtension(_name);
        System.out.println("suffix = " + suffix);

        //设置格式
        String[] array = {"jpg", "jpeg", "png", "bmp"};
        //获取文件的大小
        long _size = multipartFile.getSize();
        //设置条件
        //判断该文件是否为空,不为空进入该条件
        if (!_name.isEmpty()) {
            //判断数组是否包含该类型
            if (!Arrays.asList(array).contains(suffix)) {

                model.addAttribute(BaseNameUtils.MESSAGE, "当前系统暂不支持该文件类型");
            }
            //判断文件大小是否超出了设定
            if (_size > 1048576) {
                model.addAttribute(BaseNameUtils.MESSAGE, "当前系统只能上传约1MB大小的文件");
            }
            //防止多个相同的文件进来而进行覆盖,将采用随机数来防止这种情况
            long rondom = RandomUtils.nextInt(1000000);
            _name = rondom + "" + "_idpatcpath" + _name;
            //保存上传文件路径
            String path = request.getServletContext().getRealPath(File.separator + "statics" + File.separator + "upload");
            System.out.println("path2 = " + path);
            path = path + File.separator + _name;
            System.out.println("path = " + path);
            //如果路径不存在则创建
            File file = new File(path);
            if (!file.exists()) {
                //递归创建
                file.mkdirs();
            }

            //将 收到的文件传输给指定目标目录
            multipartFile.transferTo(file);
        }
        user.setIdPicPath(_name);
        boolean flag = userService.add(user);
        if (flag) {
            return "redirect:user/query";
        } else {
            model.addAttribute(BaseNameUtils.MESSAGE, "添加失败");
            return "forward:useradd.jsp";
        }
    }

    /**
     * 根据id查询详细信息
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "user/{id}", method = RequestMethod.GET)
    public String queryID(@PathVariable String id, Model model) {
        UserAndRole user = userService.queryUserAndRoleID(id);
        if (user != null) {
            model.addAttribute("user", user);
        }
        return "userview";
    }

    @RequestMapping("/goDelete")
    public String toDelete() {
        return "userDeleteRestFul";
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.DELETE)
    public String deleUserteID(String id, Model model) {
        if (userService.deleteUserById(Integer.valueOf(id)) == false) {
            model.addAttribute(BaseNameUtils.MESSAGE, "删除失败");
        } else {
            model.addAttribute(BaseNameUtils.MESSAGE, "删除成功");
        }
        return "redirect:user/query";
    }

    /**
     * 根据ID删除,GET请求
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/user/deleteID/{id}", method = RequestMethod.GET)
    public String deleUserID2(@PathVariable String id, Model model) {
        if (userService.deleteUserById(Integer.valueOf(id)) == false) {

        }
        return "redirect:/user/query";
    }

    /**
     * 根据id查询到修改页面
     *
     * @return
     */
    @RequestMapping(value = "/user/update/{id}", method = RequestMethod.GET)
    public String toUpdateUser(@PathVariable String id, Model model) {

        User user = new User();
        List<Role> role = new ArrayList<Role>();
        user = userService.getUserById(id);
        role = userService.queryRole();
        model.addAttribute("user", user);
        model.addAttribute("role", role);
        return "usermodify";
    }

    /**
     * 修改用户
     *
     * @param user
     * @param model
     * @return
     */
    //@RequestMapping(value = "/user", method = RequestMethod.DELETE)
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public String updateUser(User user, Model model) {
        if (!userService.modify(user)) {

        }

        return "redirect:/user/query";
    }

    /**
     * 用户添加+文件上传
     *
     * @param user
     * @param model
     * @param multipartFile
     * @param request
     * @return
     */
    @RequestMapping("/userAddMultiPart")
    public String userAddMultiPart(@Valid User user, Model model, @RequestParam(value = "multipartFile", required = false) MultipartFile multipartFile, HttpServletRequest request) throws IOException {

        //获取上传文件的名字
        String _name = multipartFile.getOriginalFilename();
        System.out.println("_name = " + _name);
        //获取上传文件的类型
        String _type = multipartFile.getContentType();
        System.out.println("_type = " + _type);
        //获取上传文件的后缀名
        String suffix = FilenameUtils.getExtension(_name);
        System.out.println("suffix = " + suffix);

        //设置格式
        String[] array = {"jpg", "jpeg", "png", "bmp"};
        //获取文件的大小
        long _size = multipartFile.getSize();
        //设置条件
        //判断该文件是否为空,不为空进入该条件
        if (!_name.isEmpty()) {
            //判断数组是否包含该类型
            if (!Arrays.asList(array).contains(suffix)) {

                model.addAttribute(BaseNameUtils.MESSAGE, "当前系统暂不支持该文件类型");
            }
            //判断文件大小是否超出了设定
            if (_size > 1048576) {
                model.addAttribute(BaseNameUtils.MESSAGE, "当前系统只能上传约1MB大小的文件");
            }
            //保存上传文件路径
            String path = request.getServletContext().getRealPath(File.separator + "upload");
            System.out.println("path2 = " + path);
            path = path + File.separator + _name;
            System.out.println("path = " + path);
            //如果路径不存在则创建
            File file = new File(path);
            if (!file.exists()) {
                //递归创建
                file.mkdirs();
            }

            //将 收到的文件传输给指定目标目录
            multipartFile.transferTo(file);
        }
        //防止多个相同的文件进来而进行覆盖,将采用随机数来防止这种情况
        long rondom = RandomUtils.nextInt(1000000);
        return "user";
    }

    /**
     * 多文件上传功能
     *
     * @param user
     * @param multipartFile
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/userAddMultiparts")
    public String userAddMultiparts(User user, @RequestParam(required = false) MultipartFile[] multipartFile, Model model, HttpServletRequest request) throws IOException {
        System.out.println("multipartFile.length = " + multipartFile.length);
        /**
         * 定义一个文件大小值数组
         */
        Long[] multipartSize = new Long[multipartFile.length];
        /**
         * x循环判断文件上传是否为空
         */
        long countSize = 0;


        for (int i = 0; i < multipartFile.length; i++) {

            /**
             * 获取上传文件路径(保存上传文件路径)
             */
            String path = request.getServletContext().getRealPath(File.separator + "statics" + File.separator + "upload");
            /**
             * 定义一个文件上传名字数组
             */
            String[] multipartNames = new String[multipartFile.length];
            /**
             * 设置随机数,防止文件重名被覆盖
             */
            long rondom = RandomUtils.nextInt(1000000);
            if (!multipartFile[i].isEmpty()) {
                /**
                 * 不为空,则获取名字
                 * 循环获取
                 */
                multipartNames[i] = multipartFile[i].getOriginalFilename();
                System.out.println("multipartNames[i] = " + multipartNames[i]);
                /**
                 * 获取文件大小值
                 */
                multipartSize[i] = multipartFile[i].getSize();
                System.out.println("multipartSize[i] = " + multipartSize[i]);
                /**
                 * 判断是否超过最大设定值
                 */
                if (multipartSize[i] > 1048576) {

                    model.addAttribute(BaseNameUtils.MESSAGE, "第" + (i + 0) + "个文件超过预期最大值");
                    System.out.println("单个文件不能1M");
                    return "";
                }
                /**
                 * 获取所有文件总最大值
                 */
                countSize = countSize + multipartSize[i];
                System.out.println("countSize = " + countSize);
                /**
                 * 判断所有文件加起来是否超过总最大设定值
                 */
                if (countSize > 5242880) {
                    System.out.println("总文件不能超过最大值");
                    model.addAttribute(BaseNameUtils.MESSAGE, "总文件超多最大值,最大值为5M");
                    return "";
                }
                /**
                 * 将名字拼接
                 */

                /**
                 * 将路径和文件名连接起来,进行传输创建
                 */
                multipartNames[i] = rondom + "" + "_idpatcpath_" + multipartNames[i];
                path = path + File.separator + multipartNames[i];
                System.out.println("path = " + path);
                /**
                 * 创建文件
                 */
                File file = new File(path);
                /**
                 * 判断是否存在该目录,不存在则创建
                 */
                if (!file.exists()) {
                    /**
                     * 递归创建
                     */
                    file.mkdirs();
                }
                //  multipartFile.transferTo(file);
                multipartFile[i].transferTo(file);
            }
        }
        return "user";
    }

    /**
     * ajax验证userCode是否唯一
     *
     * @param userCode
     * @return
     */
    @RequestMapping(value = "/userExist", method = RequestMethod.GET)
    @ResponseBody
    public String userExist(String userCode, HttpServletRequest request) {
        System.out.println("userCode : " + userCode);
        boolean flag = true;
        UserAndRole userAndRole = new UserAndRole();
        userAndRole = userService.queryUserCode(userCode);
        if (userAndRole == null) {
            flag = false;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("flag", flag);
        String json = JSON.toJSONString(map);
        return json;
    }

    /**
     * ajax查看用户详情
     * @param id
     * @return
     */

    @RequestMapping(value = "/queryParticulas",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object queryParticulas(String id){
        //System.out.println("id = " + id);
        UserAndRole user = userService.queryUserAndRoleID(id);
        Map<String, UserAndRole> map=new HashMap<String, UserAndRole>();
        if (user != null) {
            map.put("user",user);
        }
        String json=JSON.toJSONString(map);
        System.out.println("json = " + json);
        return json;
    }
}